﻿using System;
using System.Collections.Generic;
using System.Web;
using log4net;

namespace DDDProject.Components.ContextProviders
{
    /// <summary>
    /// Component that stores the context in Http Session
    /// </summary>
    /// <remarks>This context provider is useful for web environments</remarks>
    public class WebSessionContextProvider : IContextProvider
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(WebSessionContextProvider));
        private const string SESSION_CONTEXT_KEY = "DDDProject.SessionContextKey";

        public Dictionary<string, object> GetContextStore()
        {
            if (HttpContext.Current != null)
            {
                // Retrieve the context store
                Dictionary<string, object> contextStore = HttpContext.Current.Session[SESSION_CONTEXT_KEY] as Dictionary<string, object>;

                if (contextStore == null)
                {
                    // No context store : create it
                    contextStore = new Dictionary<string, object>();

                    // And store it
                    HttpContext.Current.Session[SESSION_CONTEXT_KEY] = contextStore;
                }

                // Return the context store
                return contextStore;
            }
            else
            {
                _log.Error("Error accessing current Http context");

                throw new InvalidOperationException("Cannot access current Http context...");
            }
        }
    }
}
